package com.hk.commons.validator;

import com.hk.commons.dict.DictService;
import com.hk.commons.util.CollectionUtils;
import com.hk.commons.util.Lazy;
import com.hk.commons.util.SpringContextHolder;
import com.hk.commons.validator.constraints.EnumDict;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Objects;

/**
 * @author kevin
 * @date 2018-08-31 10:57
 */
public class EnumDictValidator implements ConstraintValidator<EnumDict, Byte> {

    private boolean notNull;

    private long codeId;

    private final Lazy<DictService> dictService = Lazy.of(() -> SpringContextHolder.getBean(DictService.class));

    @Override
    public void initialize(EnumDict constraintAnnotation) {
        this.notNull = constraintAnnotation.notNull();
        this.codeId = constraintAnnotation.codeId();
    }

    @Override
    public boolean isValid(Byte value, ConstraintValidatorContext context) {
        if (Objects.isNull(value)) {
            return !notNull;
        }
        var list = dictService.get().getDictValueListByCodeId(codeId);
        return CollectionUtils.contains(list, value);
    }
}
